/*
 DNN Content Builder - sourceforge.net/projects/dnncb
 Copyright (c) 2004-2008
 by Emerson Lopes (emersonlopes@gmail.com)

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.
*/

using DotNetNuke;
using DotNetNuke.Common.Utilities;
using DNNContentBuilder;

namespace DNNContentBuilder
{
	using System;
	using System.IO;
	using System.Web;
	using System.Web.UI;
	using System.Web.UI.WebControls;
	using DotNetNuke.Entities.Modules;
	using DNNContentBuilder.UserControls;

	public interface IPopupContainer
	{
		bool PopupMode { get; set; }
	}

	/// <summary>
	///		Summary description for DNNContentBuilderModule.
	/// </summary>
	public class ContentManagerView : PortalModuleBase, DotNetNuke.Entities.Modules.IActionable, IPopupContainer
	{
		#region Constants
		private const string PopupKey = "dnncontentbuilderpopup";
		private const string FormDefinitionIdKey = "formDefinitionId";
		public const string resource = "~/DesktopModules/DNNContentBuilder/App_LocalResources/ContentManagerView";


		#endregion

		#region Controls
		protected System.Web.UI.WebControls.ImageButton btTaskList;
		protected System.Web.UI.WebControls.ImageButton btSearchContent;
		protected System.Web.UI.WebControls.ImageButton btCreateContent;
		protected System.Web.UI.WebControls.ImageButton btScheduleList;
		protected System.Web.UI.WebControls.ImageButton btEditTaxonomy;
		protected System.Web.UI.WebControls.Image imgTitle;
		protected System.Web.UI.WebControls.Literal ltMaskScripts;
        protected System.Web.UI.WebControls.Literal ltErrorMessage;

		protected System.Web.UI.WebControls.PlaceHolder plcFormEngine;
		protected System.Web.UI.WebControls.PlaceHolder plcFormSearch;
		protected System.Web.UI.WebControls.PlaceHolder plcEditTaxonomy;
		protected System.Web.UI.WebControls.PlaceHolder plcScheduleList;
		protected System.Web.UI.WebControls.PlaceHolder plcTaskList;
		protected System.Web.UI.WebControls.PlaceHolder plcHeader;
		protected System.Web.UI.WebControls.PlaceHolder plcFormEnginePopup;

		protected DNNContentBuilder.UserControls.ScheduleListControl ScheduleListControl;
		protected DNNContentBuilder.UserControls.TaskListControl TaskListControl;
		protected DNNContentBuilder.UserControls.FormEngineControl FormEngineControl;
		protected DNNContentBuilder.UserControls.TaxonomyControl TaxonomyControl;
		protected DNNContentBuilder.UserControls.FormSearchControl FormSearchControl;
		protected DNNContentBuilder.UserControls.FormEngineChildControl FormEnginePopup;
		protected System.Web.UI.WebControls.Literal txtTitle;
		protected System.Web.UI.WebControls.Label lbContentTitle;

		#endregion
	
		#region Properties
		public DotNetNuke.Entities.Modules.Actions.ModuleActionCollection ModuleActions  
		{
			get 
			{
				DotNetNuke.Entities.Modules.Actions.ModuleActionCollection actions = new DotNetNuke.Entities.Modules.Actions.ModuleActionCollection();

				actions.Add(GetNextActionID(), "Form Settings", "","","", this.EditUrl("Form Settings","","FormSettingsControl"), "", false, DotNetNuke.Security.SecurityAccessLevel.Admin, true, false);

				return actions;
			}
		}

		/// <summary>
		/// Gets or sets whether we are in Pop-Up mode
		/// </summary>
		public bool PopupMode
		{
			get
			{
				return this.plcFormEnginePopup.Visible;
			}
			set
			{
				this.plcFormEnginePopup.Visible = value;
			}
		}
		#endregion

		#region Event Handlers
		private void Page_Load(object sender, System.EventArgs e)
		{
            if (ContextUtil.GetUserId(this) == Null.NullInteger)
            {
                this.HideControls(false);
                this.ltErrorMessage.Visible = true;
                this.ShowError(DNNContentBuilder.Commons.GetLocalizedString("label_UserNotLoggedInMsg", resource),Commons.GetLocalizedString("label_UserNotLoggedInError", resource));
                return;
            }
			string script = "<script type=text/javascript>";

			try {
				using (StreamReader file = new StreamReader(HttpContext.Current.Server.MapPath("~\\DesktopModules\\DNNContentBuilder\\js\\mootools.js"))) 
				{
					script = script + file.ReadToEnd();
				}

				script = script + "\n";

				using (StreamReader file = new StreamReader(HttpContext.Current.Server.MapPath("~\\DesktopModules\\DNNContentBuilder\\js\\imask.js")))
				{
					script = script + file.ReadToEnd();
				}
			}
			catch (Exception err) {
				script = "<javascript:"+err.Message+">";
			}
			
			script = script + "</script>";

			ltMaskScripts.Text = script;

			ContentManagerSettingsController cmsController = new ContentManagerSettingsController();
			
			ContentManagerSettingsInfo cmsInfo = cmsController.GetByModule(this.ModuleId);

			if (cmsInfo != null) 
			{
				FormDefinitionController formController = new FormDefinitionController();
				FormDefinitionInfo formInfo = formController.GetItem(cmsInfo.FormDefinitionId);
				lbContentTitle.Text = formInfo.Title;
			}

			if (Request.Params[PopupKey] == "1")
			{
				DisplayFormEnginePopupMode();
			} 
			else if (!this.IsPostBack)
			{
				// If no other option has been selected, display the FormEngine by default.
				DisplayCreateContentControls();
			}
		}

		private void btTaskList_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			DisplayTaskList();
		}

		private void btSearchContent_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			DisplayFormSearch();
		}

		private void btCreateContent_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			DisplayCreateContentControls();
		}

		private void btScheduleList_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			DisplayScheduleList(); 
		}

		/// <summary>
		/// FormEngine displays a selected row from the form search pane.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		public void FormSearchControl_RowClicked(object sender, FormSearchRowClickEventArgs e)
		{
			DisplayCreateContentControls(e.MetaDataId, FormEngineDisplayMode.Update);
		}

		private void TaskListControl_TaskClicked(object sender, TaskClickEventArgs e)
		{
			DisplayCreateContentControls(e.MetaDataId, e.TaskId, FormEngineDisplayMode.Workflow);
		}

		private void btEditTaxonomy_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			DisplayEditTaxonomy();
		}
		
		#endregion

		#region Methods
        private void ShowError(string message, string error)
        {
            ltErrorMessage.Visible = true;
            ltErrorMessage.Text = @"
			<script language='javascript'>
			<!-- 
			    alert('{0}') 
			-->
			</script>
			";
            ltErrorMessage.Text = String.Format(ltErrorMessage.Text, message).Replace("\r", "").Replace("\n", "");
            ltErrorMessage.Text = ltErrorMessage.Text.Replace("<!--", "\n<!--\n").Replace("-->", "\n-->\n");
        }

		private void HideControls()
		{
			HideControls(true);
		}

		private void HideControls(bool showHeader)
		{
			foreach (System.Web.UI.Control control in this.Controls) 
			{
				if (control is System.Web.UI.WebControls.PlaceHolder) 
				{
					control.Visible = false;
				}
			}

			plcHeader.Visible = showHeader;
		}

		private void DisplayTaskList()
		{
			HideControls();
	
			this.plcTaskList.Visible = true;
	
			imgTitle.ImageUrl = "~/DesktopModules/DNNContentBuilder/images/tasks.gif";
			imgTitle.Visible = true;

			txtTitle.Text = Commons.GetLocalizedString("label_TasksTitle", resource);
			txtTitle.Visible = true;
		}

		private void DisplayFormSearch()
		{
			HideControls();
	
			this.plcFormSearch.Visible = true;
	
			imgTitle.ImageUrl = "~/DesktopModules/DNNContentBuilder/images/search.gif";
			imgTitle.Visible = true;

			txtTitle.Text = Commons.GetLocalizedString("label_SearchTitle", resource);
			txtTitle.Visible = true;
		}

		private void DisplayCreateContentControls()
		{
			HideControls();
            
			this.FormEngineControl.Clear();
			this.FormEngineControl.SetMode(FormEngineDisplayMode.Create);
			
			this.plcFormEngine.Visible = true;
	
			imgTitle.ImageUrl = "~/DesktopModules/DNNContentBuilder/images/form.gif";
            MetaDataController controller = new MetaDataController();
            MetaDataInfo info = controller.GetItem((int)HttpContext.Current.Items["metadataId"]);
			// TODO: implements txtTitle.Text = metaDataInfo.Title !! Done by Roei;
            txtTitle.Text = info.Title;
			txtTitle.Visible = false;
		}

		private void DisplayFormEnginePopupMode()
		{
			HideControls(false);
			FormEnginePopup.FormDefinitionId = Convert.ToInt32(Request.Params[FormDefinitionIdKey].ToString());
			this.PopupMode = true;
		}

		private void DisplayCreateContentControls(int metaDataId, FormEngineDisplayMode displayMode)
		{
			this.DisplayCreateContentControls();

			MetaDataController controller = new MetaDataController();
			MetaDataInfo info = controller.GetItem(metaDataId);

			string eventResource = Page.ResolveUrl("~/DesktopModules/DNNContentBuilder/App_LocalResources/MetaDataEvent");
			
			this.FormEngineControl.SetMode(displayMode);
			this.FormEngineControl.DisplayContents(info);
			
			string popUpPath = Page.ResolveUrl("~/DesktopModules/DNNContentBuilder/UserControls/MetaDataEvents.aspx");
			
			Guid parameterId = Guid.NewGuid();
			
			string parameter = ContextUtil.GetPortalId(this).ToString() + "\\" + info.MetaDataId.ToString();
			
			DataCache.SetCache(parameterId.ToString(), parameter);
			
			this.FormEngineControl.btHistory.Attributes.Add("onClick", "javascript: window.open('" + popUpPath + "?pid=" + parameterId.ToString() +"&resource=" + eventResource + "','','null,height=350,scrollbars=yes,width=600,status=yes,toolbar=no,menubar=no,location=no')");
		}

		private void DisplayCreateContentControls(int metaDataId, int taskId, FormEngineDisplayMode displayMode)
		{
			this.DisplayCreateContentControls();

			MetaDataController metaDataController = new MetaDataController();
			MetaDataTaskController taskController = new MetaDataTaskController();

			MetaDataInfo metaDataInfo = metaDataController.GetItem(metaDataId);
			MetaDataTaskInfo taskInfo = taskController.GetItem(taskId);

			this.FormEngineControl.SetMode(displayMode);

			txtTitle.Text = metaDataInfo.Title;
			txtTitle.Visible = true;
			
			this.FormEngineControl.DisplayContents(metaDataInfo, taskInfo);
		}


		private void DisplayEditTaxonomy()
		{
			HideControls();

			this.plcEditTaxonomy.Visible = true;
	
			imgTitle.ImageUrl = "~/DesktopModules/DNNContentBuilder/images/taxonomies.gif";
			imgTitle.Visible = true;

			txtTitle.Text = Commons.GetLocalizedString("label_TaxonomiesTitle", resource);
			txtTitle.Visible = true;
		}

		private void DisplayScheduleList()
		{
			HideControls();
	
			this.plcScheduleList.Visible = true;
	
			imgTitle.ImageUrl = "~/DesktopModules/DNNContentBuilder/images/schedule.gif";
			imgTitle.Visible = true;

			txtTitle.Text = Commons.GetLocalizedString("label_ScheduleTitle", resource);
			txtTitle.Visible = true;
		}
		#endregion

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.btTaskList.Click += new System.Web.UI.ImageClickEventHandler(this.btTaskList_Click);
			this.btSearchContent.Click += new System.Web.UI.ImageClickEventHandler(this.btSearchContent_Click);
			this.btCreateContent.Click += new System.Web.UI.ImageClickEventHandler(this.btCreateContent_Click);
			this.btScheduleList.Click += new System.Web.UI.ImageClickEventHandler(this.btScheduleList_Click);
			this.btEditTaxonomy.Click += new System.Web.UI.ImageClickEventHandler(this.btEditTaxonomy_Click);
			this.FormSearchControl.RowClicked += new FormSearchRowClickEventHandler(FormSearchControl_RowClicked);
			this.TaskListControl.TaskClicked += new TaskClickEventHandler(TaskListControl_TaskClicked);
			this.Load += new System.EventHandler(this.Page_Load);

		}

		#endregion
	}
}
